package com.java.advance.ticket.service.impl;

import com.java.advance.ticket.dao.TicketMapper;
import com.java.advance.ticket.redis.RedisManager;
import com.java.advance.ticket.redis.key.TicketKey;
import com.java.advance.ticket.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 方案二：缓存降级
 * Created by yangminghua on 2019/4/16.
 */
@Slf4j
@Service("ticketDowngradeService")
public class TicketServiceDowngradeImpl implements ITicketService {

    @Autowired
    TicketMapper ticketMapper;

    @Resource(name = "RedisManager")
    RedisManager redisManager;


    ConcurrentHashMap<String, String> mapLock = new ConcurrentHashMap<>();

    @Override
    public Object queryTicketStock(String ticketSeq) {
        log.info("ticketSeq:{}", ticketSeq);
        //1、先从缓存中获取该车次的余票信息
        Integer stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
        log.info("stock:{}", stock);
        if (stock != null) {
            log.info("从缓存获取数据成功");
            return stock;
        }
        boolean lock = false;
        try {
            lock = mapLock.putIfAbsent(ticketSeq, "无所谓") == null;
            if (lock) {
                //查一下缓存，做双重校验
                stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
                if (stock != null) {
                    log.info("从缓存获取数据成功");
                    return stock;
                }
                //拿到锁了，重建缓存，查数据库
                //2、缓存中没有则取数据库
                stock = ticketMapper.selectByPrimaryKey(ticketSeq).getTicketStock();
                log.info("从数据库获取数据成功");
                //3、塞到缓存当中，120秒过期
                redisManager.set(TicketKey.queryTicketStock, ticketSeq, stock);
                //4、塞到备份缓存中去
                redisManager.set(TicketKey.queryTicketStock, ticketSeq, stock);

            } else {
                //没有拿到锁
                //根据业务，进行降级
                //降级方法一：读取备份缓存
                stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
                if (stock == null) {
                    //降级方法二：返回固定值
                    stock = 0;
                    System.out.println("缓存降级了，返回固定值============");
                } else {
                    System.out.println("缓存降级了，读取备份缓存数据成功，返回备份缓存数据============");
                }
            }
        } finally {
            if (lock) {
                //释放锁
                mapLock.remove(ticketSeq);
            }
        }
        //4、返回
        return stock;
    }
}
